package common.utils.activity;

import common.utils.database.DatabaseHelper;
import common.utils.properties.SharedPreferencesUtils;

import zekezang.org.BookMarkActivity;
import zekezang.org.BookMarkAddActivity;
import zekezang.org.BookMarkHistoryActivity;
import zekezang.org.R;
import android.app.Activity;
import android.app.UiModeManager;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class MainMenu {

	private static String menuSign_book = "1";
	private static String menuSign_addBook = "2";
	private static String menuSign_reflush = "3";
	private static String menuSign_night = "4";
	private static String menuSign_history = "5";
	private static String menuSign_makeMain = "6";
	private static String menuSign_fullscreen = "7";
	private static String menuSign_exit = "8";
	private static String set_main_page = "main_page";
	private static String set_full_screen = "full_screen";
	private static String set_mode_screen = "mode_screen";

	private PopupWindow mainPopupWindow = null;
	private PopupWindow subPopupWindow = null;

	private Context context = null;
	private View tokenView = null;

	private WebView webView = null;
	private Activity activity = null;
	private String menuSign = null;
	private Handler handler = null;

	private int[] resArray = new int[] { R.drawable.book, R.drawable.add_book, R.drawable.reflush, R.drawable.reflush,
			R.drawable.history, R.drawable.setting_home, R.drawable.cancel_home, R.drawable.menu_exit };
	private String[] title = new String[] { "书签", "加入书签", "刷新", "黑夜模式", "历史", "设为主页", "全屏", "退出" };

	private int[] resArray_oppose = new int[] { R.drawable.book, R.drawable.add_book, R.drawable.reflush,
			R.drawable.reflush, R.drawable.history, R.drawable.setting_home, R.drawable.cancel_home,
			R.drawable.menu_exit };
	private String[] title_oppose = new String[] { "书签", "加入书签", "刷新", "黑夜模式", "历史", "取消主页", "退出全屏", "退出" };

	private int[] subResArray = new int[] {};
	private String[] subTitle = new String[] {};

	private MainMenu(Activity activity, Context context, View tokenView, WebView webView, String menuSign,
			Handler handler) {
		// TODO Auto-generated constructor stub
		this.context = context;
		this.tokenView = tokenView;
		this.webView = webView;
		this.activity = activity;
		this.menuSign = menuSign;
		this.handler = handler;
		initPopupWindow();
	}

	private static MainMenu mainMenu = null;

	public static MainMenu getInstance(Activity activity, Context context, View tokenView, WebView webView,
			String menuSign, Handler handler) {
		if (null == mainMenu) {
			return new MainMenu(activity, context, tokenView, webView, menuSign, handler);
		} else {
			return mainMenu;
		}
	}

	public void responseOnKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU && mainPopupWindow.isShowing()) {
			mainPopupWindow.dismiss();
			if (subPopupWindow.isShowing()) {
				subPopupWindow.dismiss();
			}
		} else if (keyCode == KeyEvent.KEYCODE_MENU && !mainPopupWindow.isShowing()) {
			mainPopupWindow.showAtLocation(tokenView, Gravity.BOTTOM, 0, 35);
		} else {

		}
	}

	public void responseOnKeyDown() {
		if (mainPopupWindow.isShowing()) {
			mainPopupWindow.dismiss();
			if (subPopupWindow.isShowing()) {
				subPopupWindow.dismiss();
			}
		} else if (!mainPopupWindow.isShowing()) {
			mainPopupWindow.showAtLocation(tokenView, Gravity.BOTTOM, 0, 35);
		} else {
		}
	}

	public void responseOnTouch() {
		if (mainPopupWindow.isShowing()) {
			mainPopupWindow.dismiss();
		}
	}

	private void initPopupWindow() {

		View view = LayoutInflater.from(context).inflate(R.layout.main_menu, null);
		GridView mainGridView = (GridView) view.findViewById(R.id.menuGridChange);
		mainGridView.setAdapter(new MainImageAdapter(context));
		// 用Popupwindow弹出menu
		mainPopupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		mainPopupWindow.setAnimationStyle(zekezang.org.R.style.PopupAnimation);

		View subView = LayoutInflater.from(context).inflate(R.layout.sub_menu, null);
		GridView subGridView = (GridView) subView.findViewById(R.id.menuGridChange);
		subGridView.setAdapter(new SubImageAdapter(context));
		subPopupWindow = new PopupWindow(subView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		subPopupWindow.setAnimationStyle(R.style.PopupAnimation);

	}

	public class MainImageAdapter extends BaseAdapter {

		private Context context;

		public MainImageAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			return resArray.length;
		}

		@Override
		public Object getItem(int i) {
			return resArray[i];
		}

		@Override
		public long getItemId(int i) {
			return i;
		}

		@Override
		public View getView(int i, View arg1, ViewGroup arg2) {
			LinearLayout linear = new LinearLayout(context);
			linear.setBackgroundResource(R.drawable.menu_click_drawable);
			linear.setOrientation(LinearLayout.VERTICAL);

			LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params.gravity = Gravity.CENTER;

			// 实现ontouch事件

			AddBook(i, linear, params);
			book(i, linear, params);
			reflush(i, linear, params);
			lightModel(i, linear, params);
			history(i, linear, params);
			settingMainWeb(i, linear, params);
			outFullScreen(i, linear, params);
			exits(i, linear, params);

			return linear;
		}

		// 书签
		private void book(int i, LinearLayout linear, LinearLayout.LayoutParams params) {
			if (0 == i) {
				ImageView iv = new ImageView(context);
				TextView tv = new TextView(context);
				if (menuSign.contains(menuSign_book)) {

					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							ActivityUtils.getInstance().leftIN_rightOUT_Transition(activity, context,
									BookMarkActivity.class);
							responseOnTouch();
						}
					});
				} else {
					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);
					linear.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
						}
					});
					linear.setEnabled(false);
				}

			}
		}

		// 添加书签
		private void AddBook(int i, LinearLayout linear, LinearLayout.LayoutParams params) {
			if (1 == i) {
				ImageView iv = new ImageView(context);
				TextView tv = new TextView(context);
				if (menuSign.contains(menuSign_addBook)) {
					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							ActivityUtils.getInstance()
									.leftIN_rightOUT_Transition(activity, context, BookMarkAddActivity.class,
											"uriData", webView.getUrl() + "###" + webView.getTitle());
							responseOnTouch();
						}
					});
				} else {
					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
						}
					});
					linear.setEnabled(false);
				}
			}
		}

		// 刷新
		private void reflush(int i, LinearLayout linear, LinearLayout.LayoutParams params) {
			if (2 == i) {
				ImageView iv = new ImageView(context);
				TextView tv = new TextView(context);
				if (menuSign.contains(menuSign_reflush)) {

					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							handler.sendEmptyMessage(3);
							webView.reload();
						}
					});
				} else {
					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
						}
					});
					linear.setEnabled(false);
				}
			}
		}

		// 黑夜
		private void lightModel(int i, LinearLayout linear, LinearLayout.LayoutParams params) {
			if (3 == i) {
				ImageView iv = new ImageView(context);
				TextView tv = new TextView(context);
				if (menuSign.contains(menuSign_night)) {

					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							UiModeManager uiModeManager = (UiModeManager)context.getSystemService(Context.UI_MODE_SERVICE);
							if(!SharedPreferencesUtils.compare(context, set_mode_screen, "yes")){
								SharedPreferencesUtils.setSharedPref(context, set_mode_screen, "yes");
								
//								uiModeManager.enableCarMode(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME);
								uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
							}else{
								SharedPreferencesUtils.removeSharedPref(context, set_mode_screen);
								
//								uiModeManager.disableCarMode(UiModeManager.DISABLE_CAR_MODE_GO_HOME);
								uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
								
							}
							
						}
					});
				} else {
					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
						}
					});
					linear.setEnabled(false);
				}
			}
		}

		private void history(int i, LinearLayout linear, LinearLayout.LayoutParams params) {
			if (4 == i) {
				ImageView iv = new ImageView(context);
				TextView tv = new TextView(context);
				if (menuSign.contains(menuSign_history)) {
					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							ActivityUtils.getInstance().leftIN_rightOUT_Transition(activity, context,
									BookMarkHistoryActivity.class);
							responseOnTouch();
						}
					});
				} else {

					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
						}
					});
					linear.setEnabled(false);
				}
			}
		}

		// 设为主页
		private void settingMainWeb(final int i, LinearLayout linear, LinearLayout.LayoutParams params) {
			if (5 == i) {
				final ImageView iv = new ImageView(context);
				final TextView tv = new TextView(context);
				if (menuSign.contains(menuSign_makeMain)) {

					if (!SharedPreferencesUtils.compare(context, set_main_page, webView.getUrl())) {
						iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i]))
								.getBitmap());
						linear.addView(iv, params);
						tv.setText(title[i]);
						linear.addView(tv, params);
					} else {
						iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i]))
								.getBitmap());
						linear.addView(iv, params);
						tv.setText(title_oppose[i]);
						linear.addView(tv, params);
					}

					linear.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							String sql = null;
							String uri = webView.getUrl();
							
							if (!SharedPreferencesUtils.compare(context, set_main_page, webView.getUrl())) {
								SharedPreferencesUtils.setSharedPref(context, set_main_page, uri);
								
								iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i]))
										.getBitmap());
								tv.setText(title_oppose[i]);
								
								bookMarkInSqlite(uri, webView.getTitle());
								SQLiteDatabase sqLiteDatabase = null;
								try {
									sqLiteDatabase = new DatabaseHelper(context, "book_DB").getWritableDatabase();
									sqLiteDatabase.beginTransaction();
									sqLiteDatabase.execSQL("update book set mainWeb = 0");
									sql = "update book set mainWeb = 1 where uri = '" + uri + "'";
									sqLiteDatabase.execSQL(sql);
									sqLiteDatabase.setTransactionSuccessful();
									Toast.makeText(context, R.string.main_web_toast, Toast.LENGTH_SHORT).show();
								} catch (SQLException e) {
									e.printStackTrace();
								} finally {
									if (sqLiteDatabase != null) {
										sqLiteDatabase.endTransaction();
										sqLiteDatabase.close();
									}
								}
							}else{
								SharedPreferencesUtils.removeSharedPref(context, set_main_page);
								iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i]))
										.getBitmap());
								tv.setText(title[i]);
								
								SQLiteDatabase sqLiteDatabase = null;
								try {
									sqLiteDatabase = new DatabaseHelper(context, "book_DB").getWritableDatabase();
									sqLiteDatabase.execSQL("update book set mainWeb = 0");
									Toast.makeText(context, R.string.cancel_main_web_toast, Toast.LENGTH_SHORT).show();
								} catch (SQLException e) {
									e.printStackTrace();
								} finally {
									if (sqLiteDatabase != null) {
										sqLiteDatabase.close();
									}
								}
							}
							
						}
					});

				} else {

					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);
					linear.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
						}
					});
					linear.setEnabled(false);
				}
			}
		}

		// 全屏
		private void outFullScreen(final int i, LinearLayout linear, LinearLayout.LayoutParams params) {
			if (6 == i) {
				final ImageView iv = new ImageView(context);
				final TextView tv = new TextView(context);
				if (menuSign.contains(menuSign_fullscreen)) {

					if (!SharedPreferencesUtils.compare(context, set_full_screen, "yes")) {
						iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i]))
								.getBitmap());
						linear.addView(iv, params);
						tv.setText(title_oppose[i]);
						linear.addView(tv, params);
					} else {
						iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i]))
								.getBitmap());
						linear.addView(iv, params);
						tv.setText(title[i]);
						linear.addView(tv, params);
					}

					linear.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							
							if(!SharedPreferencesUtils.compare(context, set_full_screen, "yes")){
								
								SharedPreferencesUtils.setSharedPref(context, set_full_screen, "yes");
								iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i]))
										.getBitmap());
								tv.setText(title[i]);
								Toast.makeText(context, "退出全屏模式", Toast.LENGTH_SHORT).show();
							}else{
								SharedPreferencesUtils.removeSharedPref(context, set_full_screen);
								iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i]))
										.getBitmap());
								tv.setText(title_oppose[i]);
								Toast.makeText(context, "全屏模式", Toast.LENGTH_SHORT).show();
							}
							
						}
					});
				} else {

					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
						}
					});
					linear.setEnabled(false);
				}
			}
		}

		// 退出
		private void exits(int i, LinearLayout linear, LinearLayout.LayoutParams params) {
			if (7 == i) {
				ImageView iv = new ImageView(context);
				TextView tv = new TextView(context);
				if (menuSign.contains(menuSign_exit)) {
					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							ActivityUtils.getInstance().exitClient(context);
						}
					});
				} else {
					iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(resArray[i])).getBitmap());
					linear.addView(iv, params);
					tv.setText(title[i]);
					linear.addView(tv, params);

					linear.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
						}
					});
					linear.setEnabled(false);
				}
			}
		}

		private void bookMarkInSqlite(String url, String title) {
			SQLiteDatabase sqLiteDatabase = null;
			sqLiteDatabase = new DatabaseHelper(context, "book_DB").getReadableDatabase();
			Cursor cursor = sqLiteDatabase.rawQuery("select count(id) as ids from book where uri = ?",
					new String[] { url });
			Integer sign = 0;
			while (cursor.moveToNext()) {
				sign = cursor.getInt(cursor.getColumnIndex("ids"));
			}
			sqLiteDatabase.close();
			if (sign <= 0) {
				sqLiteDatabase = new DatabaseHelper(context, "book_DB").getWritableDatabase();
				try {
					sqLiteDatabase.beginTransaction();
					sqLiteDatabase.execSQL("insert into book (uriDescription,uri) values (?, ?)", new Object[] { title,
							url });
					sqLiteDatabase.setTransactionSuccessful();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					sqLiteDatabase.endTransaction();
					sqLiteDatabase.close();
				}
			} else {
			}
		}

	}

	public class SubImageAdapter extends BaseAdapter {
		private Context context;

		public SubImageAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			return subResArray.length;
		}

		@Override
		public Object getItem(int i) {
			return subResArray[i];
		}

		@Override
		public long getItemId(int i) {
			return i;
		}

		@Override
		public View getView(int i, View arg1, ViewGroup arg2) {
			LinearLayout linear = new LinearLayout(context);
			linear.setOrientation(LinearLayout.VERTICAL);

			ImageView iv = new ImageView(context);
			iv.setImageBitmap(((BitmapDrawable) context.getResources().getDrawable(subResArray[i])).getBitmap());
			LinearLayout.LayoutParams params2 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params2.gravity = Gravity.CENTER;
			linear.addView(iv, params2);

			TextView tv = new TextView(context);
			tv.setText(subTitle[i]);
			LinearLayout.LayoutParams params3 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params3.gravity = Gravity.CENTER;

			linear.addView(tv, params3);

			// 实现ontouch事件

			return linear;
		}
	}
}
